#!/bin/bash
# Copyright (C) 2012 Daniel Wasilew <daniel.wasilew@codeminer.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
WORKING_DIR="/media/data"
BIN_DIR="$WORKING_DIR/bin"
EXEC="java -jar $WORKING_DIR/bin/parts-server.jar"
UPDATE_FILE="$WORKING_DIR/tmp/current.tar.gz"
TMP_LOCATION="/tmp/update"

do_update() {
	if [ -d $TMP_LOCATION ]
 	then
		echo "will delete old tmp location"
		rm -r $TMP_LOCATION
 	fi 
		echo "creating tmp location"
		mkdir $TMP_LOCATION
		echo "moving old bin to $TMP_LOCATION"
		mv "$BIN_DIR/" $TMP_LOCATION
		echo "creating new bin directory"
		mkdir "$BIN_DIR"
		echo "unpacking update file to $BIN_DIR"
		tar xf $UPDATE_FILE -C $BIN_DIR
		echo "removing $UPDATE_FILE"
		rm $UPDATE_FILE
}

while :
do
	if [ -e $UPDATE_FILE ]
	then
		echo "update file found, will now remove old version and unpack new version"
		do_update
	fi
	#start parts-server
	$EXEC
	echo "will restart parts-server in 15 seconds"
	sleep 15
done


